package com.test.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.test.dao.GoodsDao;
import com.test.entity.Goods;
import com.test.entity.Response;
import com.test.service.GoodsService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    GoodsDao goodsDao;


    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public List<Goods> queryAllGoods() {
        return goodsDao.queryAllGoods();
    }

    // @CacheEvict(cacheNames = "goods",key = "#gdId")
    @Override
    public boolean deleteById(int gdId) {
        boolean flag = goodsDao.deleteById(gdId) > 0;
        redisTemplate.delete("goods_"+gdId);
        return flag;
    }

    @Override
    public PageInfo<Goods> queryAllByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Goods> goods = goodsDao.queryAllGoods();
        PageInfo<Goods> pageInfo = new PageInfo<>(goods);
        return pageInfo;
    }

    // @Cacheable(cacheNames = "goods",key = "#id")
    @Override
    public Response<Goods> queryById(Integer id) {
        // 从缓存中查数据
        Object obj = redisTemplate.opsForValue().get("goods_" + id);
        // you 直接返回结果
        if (obj != null) {
            return (Response<Goods>) obj;
        }
        // 如果没有，查询数据库，然后把数据放到缓存中
        Response<Goods> r = Response.success(goodsDao.queryById(id));
        redisTemplate.opsForValue().set("goods_" + id,r,5, TimeUnit.HOURS);
        return r;
    }

    @Override
    public Response<Goods> insert(Goods goods) {
        Response<Goods> r = null;
        if (goods.getPrice() == null || goods.getPrice() <= 0) {
            r = Response.fail("商品价格范围不正确");
            return r;
        }
        int num = goodsDao.insert(goods);
        if (num > 0) {
            r = Response.success("商品【" + goods.getId() + "---" + goods.getName() + "】添加成功！", goods);
        } else {
            r = Response.fail("商品添加失败");
        }
        return r;
    }

    // @CachePut(cacheNames = "goods",key = "#goods.id" )
    @Override
    public Response<Goods> update(Goods goods) {
        Response<Goods> r = null;
        if (goods.getPrice() == null || goods.getPrice() <= 0) {
            r = Response.fail("商品价格范围不正确");
            return r;
        }
        int num = goodsDao.update(goods);

        if (num > 0) {
            r = Response.success("商品【" + goods.getName() + "】更新成功！", goods);
            redisTemplate.opsForValue().set("goods_" + goods.getId(),r);
        } else {
            r = Response.fail("更新成功失败");
        }
        return r;
    }
}
